package com.neulogistics.contrib.warehouse.api.application.integrationevent.handler;

import com.blackto.lib.eventbus.abstraction.IIntegrationEventHandler;
import com.neulogistics.contrib.warehouse.api.application.integrationevent.subscribe.PurchaseOrderCreatedIntegrationEvent;
import com.neulogistics.contrib.warehouse.domain.model.aggregate.CirculationOrder;
import com.neulogistics.contrib.warehouse.domain.model.enumeration.CirculationDetail;
import com.neulogistics.contrib.warehouse.domain.model.enumeration.CirculationType;
import com.neulogistics.contrib.warehouse.domain.model.valueobject.GoodsItem;
import com.neulogistics.contrib.warehouse.domain.repository.ICirculationOrderRepository;
import com.neulogistics.infrastructure.cache.idservice.RedisIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class PurchaseOrderCreatedIntegrationEventHandler implements IIntegrationEventHandler<PurchaseOrderCreatedIntegrationEvent> {
    @Resource
    ICirculationOrderRepository circulationOrderRepository;

    @Resource
    RedisIdUtil redisIdUtil;

    private final String CirculationOrder_Id_Key;

    public PurchaseOrderCreatedIntegrationEventHandler(@Value("${spring.application.name}") String appName) {
        CirculationOrder_Id_Key = appName + ":" + "circulationOrderId";
    }

    @Override
    public CompletableFuture<Void> handle(PurchaseOrderCreatedIntegrationEvent event) {
        // 生成进货入库单
        Long circulationId = redisIdUtil.nextId(CirculationOrder_Id_Key);
        List<GoodsItem> goodsItems = Arrays.asList(event.goodsItem);
        CirculationOrder circulationOrder = new CirculationOrder(circulationId, event.warehouseId, CirculationType.Inbound,
                CirculationDetail.Purchase_Inbound, null, goodsItems);

        circulationOrderRepository.save(circulationOrder);

        return CompletableFuture.completedFuture(null);
    }
}
